// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.Product;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.BrandMapper;
import com.fowo.api.mapper.ClassifyMapper;
import com.fowo.api.mapper.ProductCustomsPriceMapper;
import com.fowo.api.mapper.ProductGroupMapper;
import com.fowo.api.mapper.ProductIngredientsMapper;
import com.fowo.api.mapper.ProductInventoryMapper;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.mapper.ProductPackMapper;
import com.fowo.api.mapper.ProductQualityCheckMapper;
import com.fowo.api.mapper.ProductSpuSubMapper;
import com.fowo.api.mapper.ProductSubMapper;
import com.fowo.api.mapper.ProductSupplierQuoteMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.brand.BrandItemVo;
import com.fowo.api.model.brand.BrandSearchParamPo;
import com.fowo.api.model.classify.ClassifyItemVo;
import com.fowo.api.model.classify.ClassifySearchParamPo;
import com.fowo.api.model.product.ProductExcelPo;
import com.fowo.api.model.product.ProductGetPurchaseOrderParam;
import com.fowo.api.model.product.ProductGetPurchaseOrderResult;
import com.fowo.api.model.product.ProductGetStorageBinParam;
import com.fowo.api.model.product.ProductGetStorageBinResult;
import com.fowo.api.model.product.ProductImportPo;
import com.fowo.api.model.product.ProductItemVo;
import com.fowo.api.model.product.ProductSearchParamPo;
import com.fowo.api.model.product.ProductVo;
import com.fowo.api.model.product.customs.price.ProductCustomsPriceSearchParamPo;
import com.fowo.api.model.product.group.ProductGroupItemVo;
import com.fowo.api.model.product.group.ProductGroupSearchParamPo;
import com.fowo.api.model.product.ingredients.ProductIngredientsSearchParamPo;
import com.fowo.api.model.product.inventory.ProductInventorySearchParamPo;
import com.fowo.api.model.product.pack.ProductPackSearchParamPo;
import com.fowo.api.model.product.quality.check.ProductQualityCheckSearchParamPo;
import com.fowo.api.model.product.spu.sub.ProductSpuSubSearchParamPo;
import com.fowo.api.model.product.sub.ProductSubSearchParamPo;
import com.fowo.api.model.product.supplier.quote.ProductSupplierQuoteSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.ProductCustomsPriceService;
import com.fowo.api.service.ProductIngredientsService;
import com.fowo.api.service.ProductInventoryService;
import com.fowo.api.service.ProductPackService;
import com.fowo.api.service.ProductQualityCheckService;
import com.fowo.api.service.ProductService;
import com.fowo.api.service.ProductSpuSubService;
import com.fowo.api.service.ProductSubService;
import com.fowo.api.service.ProductSupplierQuoteService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.mapper.SysUserMapper;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.model.SysUserItemVo;
import com.fowo.api.sys.model.SysUserSearch;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 产品 服务实现基类
 * @author 蜂窝蜜造平台 配置人：王阳阳，吕家傲
 */
@Slf4j
@DataObjectType(Product.class)
@DS("ds24")
public class ProductBaseServiceImpl
  extends ServiceImpl<ProductMapper, Product>
  implements ProductService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("createUserName", "su.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected ProductService self;

  @Resource
  protected ProductSupplierQuoteService productSupplierQuoteService;

  @Resource
  protected ProductIngredientsService productIngredientsService;

  @Resource
  protected ProductPackService productPackService;

  @Resource
  protected ProductCustomsPriceService productCustomsPriceService;

  @Resource
  protected ProductQualityCheckService productQualityCheckService;

  @Resource
  protected ProductInventoryService productInventoryService;

  @Resource
  protected ProductSubService productSubService;

  @Resource
  protected ProductSpuSubService productSpuSubService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected ClassifyMapper classifyMapper;

  @Resource
  protected BrandMapper brandMapper;

  @Resource
  protected SysUserMapper sysUserMapper;

  @Resource
  protected ProductGroupMapper productGroupMapper;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Resource
  protected Validator validator;

  /**
   * 创建产品
   * @param model 产品
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(ProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Product entity = new Product();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getIsOpen() == null) {
      entity.setIsOpen(false);
    }

    if (model.getIsMatchedAlibaba() == null) {
      entity.setIsMatchedAlibaba(false);
    }

    if (model.getIsMatchedListing() == null) {
      entity.setIsMatchedListing(false);
    }

    if (model.getType() == null) {
      entity.setType("CP01");
    }

    if (model.getIsBatch() == null) {
      entity.setIsBatch(false);
    }
    // 类别名 默认值设置
    if (!StringUtils.hasText(model.getProductType())) {
      model.setProductType("'CP01'");
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return entity.getId();
    }
    throw new Exception("产品保存失败");
  }

  /**
   * 更新所有子表
   * @param model 产品
   */
  protected void updateAllChilds(ProductVo model) throws Exception {
    if (model.getProductSupplierQuote() != null) {
      productSupplierQuoteService.saveAllByParentProduct(
        model.getId(),
        model.getProductSupplierQuote()
      );
    }

    if (model.getIngredients() != null) {
      productIngredientsService.saveAllByProductId(
        model.getId(),
        model.getIngredients()
      );
    }

    if (model.getPacks() != null) {
      productPackService.saveAllByProductId(model.getId(), model.getPacks());
    }

    if (model.getCustoms() != null) {
      productCustomsPriceService.saveAllByProductId(
        model.getId(),
        model.getCustoms()
      );
    }

    if (model.getChecks() != null) {
      productQualityCheckService.saveAllByProductId(
        model.getId(),
        model.getChecks()
      );
    }

    if (model.getInventorys() != null) {
      productInventoryService.saveAllByItemId(
        model.getId(),
        model.getInventorys()
      );
    }

    if (model.getSubProducts() != null) {
      productSubService.saveAllByProductId(
        model.getId(),
        model.getSubProducts()
      );
    }

    if (model.getSubProductsSpu() != null) {
      productSpuSubService.saveAllByProductId(
        model.getId(),
        model.getSubProductsSpu()
      );
    }
  }

  /**
   * 更新产品
   * @param model 产品
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(ProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Product entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("产品不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createUser",
      "accessoriesNum",
      "createTime",
      "lastUpdateTime",
      "lastUpdateUser",
      "inventorys"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return true;
    }
    return false;
  }/**
   * 更新产品（带空值）
   * @param model 产品
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(ProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Product entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("产品不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(
        model.getPicUrl() != null,
        Product::getPicUrl,
        JSON.toJSONString(model.getPicUrl())
      )
      .setSql(model.getPicUrl() == null, "pic_url = null")
      .set(Product::getSpuName, model.getSpuName())
      .set(Product::getSpu, model.getSpu())
      .set(Product::getName, model.getName())
      .set(Product::getSku, model.getSku())
      .set(Product::getIsOpen, model.getIsOpen())
      .set(Product::getModel, model.getModel())
      .set(Product::getUnit, model.getUnit())
      .set(Product::getClassify, model.getClassify())
      .set(Product::getClassifyName, model.getClassifyName())
      .set(Product::getBrand, model.getBrand())
      .set(Product::getBrandName, model.getBrandName())
      .set(Product::getDeveloper, model.getDeveloper())
      .set(Product::getDeveloperName, model.getDeveloperName())
      .set(
        model.getPrincipal() != null,
        Product::getPrincipal,
        JSON.toJSONString(model.getPrincipal())
      )
      .setSql(model.getPrincipal() == null, "principal = null")
      .set(Product::getPrincipalName, model.getPrincipalName())
      .set(Product::getBuyer, model.getBuyer())
      .set(Product::getBuyerName, model.getBuyerName())
      .set(Product::getSalesStatus, model.getSalesStatus())
      .set(Product::getIsMatchedAlibaba, model.getIsMatchedAlibaba())
      .set(Product::getIsMatchedListing, model.getIsMatchedListing())
      .set(Product::getLastUpdateTime, model.getLastUpdateTime())
      .set(Product::getType, model.getType())
      .set(Product::getProductType, model.getProductType())
      .set(Product::getGroup, model.getGroup())
      .set(Product::getGroupName, model.getGroupName())
      .set(Product::getLastUpdateUser, model.getLastUpdateUser())
      .set(Product::getLabel, model.getLabel())
      .set(Product::getLifeTag, model.getLifeTag())
      .set(Product::getInfo1, model.getInfo1())
      .set(Product::getInfo2, model.getInfo2())
      .set(Product::getEpColor, model.getEpColor())
      .set(Product::getProductDescription, model.getProductDescription())
      .set(
        model.getAttachment() != null,
        Product::getAttachment,
        JSON.toJSONString(model.getAttachment())
      )
      .setSql(model.getAttachment() == null, "attachment = null")
      .set(Product::getMaterial, model.getMaterial())
      .set(Product::getTradeName, model.getTradeName())
      .set(Product::getLxProductId, model.getLxProductId())
      .set(Product::getAttribute, model.getAttribute())
      .eq(Product::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(model.getId());
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(ProductSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 供应商报价(productSupplierQuote) 对应的对象
    ProductSupplierQuoteSearchParamPo productSupplierQuoteSearchParam =
      new ProductSupplierQuoteSearchParamPo();
    productSupplierQuoteSearchParam.setDisableDataPremissions(true);
    productSupplierQuoteSearchParam.setParentProductInList(ids);
    ProductSupplierQuoteMapper localProductSupplierQuoteMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductSupplierQuoteMapper.class);
    productSupplierQuoteSearchParam.applySqlSegments();
    List<Long> productSupplierQuoteIdList =
      localProductSupplierQuoteMapper.searchIds(
        productSupplierQuoteSearchParam
      );
    if (!productSupplierQuoteIdList.isEmpty()) {
      ProductSupplierQuoteService localProductSupplierQuoteService =
        ContextHolder
          .getApplicationContext()
          .getBean(ProductSupplierQuoteService.class);
      localProductSupplierQuoteService.batchDelete(productSupplierQuoteIdList);
    }

    // 处理子表字段 关联辅料(ingredients) 对应的对象
    ProductIngredientsSearchParamPo ingredientsSearchParam =
      new ProductIngredientsSearchParamPo();
    ingredientsSearchParam.setDisableDataPremissions(true);
    ingredientsSearchParam.setProductIdInList(ids);
    ProductIngredientsMapper localProductIngredientsMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductIngredientsMapper.class);
    ingredientsSearchParam.applySqlSegments();
    List<Long> ingredientsIdList = localProductIngredientsMapper.searchIds(
      ingredientsSearchParam
    );
    if (!ingredientsIdList.isEmpty()) {
      ProductIngredientsService localProductIngredientsService = ContextHolder
        .getApplicationContext()
        .getBean(ProductIngredientsService.class);
      localProductIngredientsService.batchDelete(ingredientsIdList);
    }

    // 处理子表字段 辅料&包材(可选)(packs) 对应的对象
    ProductPackSearchParamPo packsSearchParam = new ProductPackSearchParamPo();
    packsSearchParam.setDisableDataPremissions(true);
    packsSearchParam.setProductIdInList(ids);
    ProductPackMapper localProductPackMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductPackMapper.class);
    packsSearchParam.applySqlSegments();
    List<Long> packsIdList = localProductPackMapper.searchIds(packsSearchParam);
    if (!packsIdList.isEmpty()) {
      ProductPackService localProductPackService = ContextHolder
        .getApplicationContext()
        .getBean(ProductPackService.class);
      localProductPackService.batchDelete(packsIdList);
    }

    // 处理子表字段 报关清关费用(customs) 对应的对象
    ProductCustomsPriceSearchParamPo customsSearchParam =
      new ProductCustomsPriceSearchParamPo();
    customsSearchParam.setDisableDataPremissions(true);
    customsSearchParam.setProductIdInList(ids);
    ProductCustomsPriceMapper localProductCustomsPriceMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductCustomsPriceMapper.class);
    customsSearchParam.applySqlSegments();
    List<Long> customsIdList = localProductCustomsPriceMapper.searchIds(
      customsSearchParam
    );
    if (!customsIdList.isEmpty()) {
      ProductCustomsPriceService localProductCustomsPriceService = ContextHolder
        .getApplicationContext()
        .getBean(ProductCustomsPriceService.class);
      localProductCustomsPriceService.batchDelete(customsIdList);
    }

    // 处理子表字段 质检标准(checks) 对应的对象
    ProductQualityCheckSearchParamPo checksSearchParam =
      new ProductQualityCheckSearchParamPo();
    checksSearchParam.setDisableDataPremissions(true);
    checksSearchParam.setProductIdInList(ids);
    ProductQualityCheckMapper localProductQualityCheckMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductQualityCheckMapper.class);
    checksSearchParam.applySqlSegments();
    List<Long> checksIdList = localProductQualityCheckMapper.searchIds(
      checksSearchParam
    );
    if (!checksIdList.isEmpty()) {
      ProductQualityCheckService localProductQualityCheckService = ContextHolder
        .getApplicationContext()
        .getBean(ProductQualityCheckService.class);
      localProductQualityCheckService.batchDelete(checksIdList);
    }

    // 处理子表字段 库存情况(inventorys) 对应的对象
    ProductInventorySearchParamPo inventorysSearchParam =
      new ProductInventorySearchParamPo();
    inventorysSearchParam.setDisableDataPremissions(true);
    inventorysSearchParam.setItemIdInList(ids);
    ProductInventoryMapper localProductInventoryMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductInventoryMapper.class);
    inventorysSearchParam.applySqlSegments();
    List<Long> inventorysIdList = localProductInventoryMapper.searchIds(
      inventorysSearchParam
    );
    if (!inventorysIdList.isEmpty()) {
      ProductInventoryService localProductInventoryService = ContextHolder
        .getApplicationContext()
        .getBean(ProductInventoryService.class);
      localProductInventoryService.batchDelete(inventorysIdList);
    }

    // 处理子表字段 包含产品(subProducts) 对应的对象
    ProductSubSearchParamPo subProductsSearchParam =
      new ProductSubSearchParamPo();
    subProductsSearchParam.setDisableDataPremissions(true);
    subProductsSearchParam.setProductIdInList(ids);
    ProductSubMapper localProductSubMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductSubMapper.class);
    subProductsSearchParam.applySqlSegments();
    List<Long> subProductsIdList = localProductSubMapper.searchIds(
      subProductsSearchParam
    );
    if (!subProductsIdList.isEmpty()) {
      ProductSubService localProductSubService = ContextHolder
        .getApplicationContext()
        .getBean(ProductSubService.class);
      localProductSubService.batchDelete(subProductsIdList);
    }

    // 处理子表字段 款式属性(subProductsSpu) 对应的对象
    ProductSpuSubSearchParamPo subProductsSpuSearchParam =
      new ProductSpuSubSearchParamPo();
    subProductsSpuSearchParam.setDisableDataPremissions(true);
    subProductsSpuSearchParam.setProductIdInList(ids);
    ProductSpuSubMapper localProductSpuSubMapper = ContextHolder
      .getApplicationContext()
      .getBean(ProductSpuSubMapper.class);
    subProductsSpuSearchParam.applySqlSegments();
    List<Long> subProductsSpuIdList = localProductSpuSubMapper.searchIds(
      subProductsSpuSearchParam
    );
    if (!subProductsSpuIdList.isEmpty()) {
      ProductSpuSubService localProductSpuSubService = ContextHolder
        .getApplicationContext()
        .getBean(ProductSpuSubService.class);
      localProductSpuSubService.batchDelete(subProductsSpuIdList);
    }
  }

  /**
   * 删除产品
   * @param id 产品的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除产品
   * @param ids 产品的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<ProductImportPo> excelToImportRow(
    ProductImportPo row,
    Integer rowNumber,
    ProductVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<ProductImportPo> ir = new ImportRow<ProductImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<ProductImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new ProductVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, ProductImportPo.class);

    // 一般数据处理
    vo.setIsOpen(SheetUtils.tryToBoolean(row.getIsOpen()));
    vo.setPurchasingDeliveryTime(
      SheetUtils.tryToInteger(row.getPurchasingDeliveryTime())
    );
    vo.setProcurementCost(
      SheetUtils.tryToDecimal(
        row.getProcurementCost(),
        new String[] { "￥" },
        null
      )
    );
    vo.setPackingNum(SheetUtils.tryToInteger(row.getPackingNum()));
    vo.setBoxLength(SheetUtils.tryToDecimal(row.getBoxLength()));
    vo.setBoxWidth(SheetUtils.tryToDecimal(row.getBoxWidth()));
    vo.setBoxHeight(SheetUtils.tryToDecimal(row.getBoxHeight()));
    vo.setPackingWeight(SheetUtils.tryToDecimal(row.getPackingWeight()));
    vo.setPackageLength(SheetUtils.tryToDecimal(row.getPackageLength()));
    vo.setPackageWidth(SheetUtils.tryToDecimal(row.getPackageWidth()));
    vo.setPackageHeight(SheetUtils.tryToDecimal(row.getPackageHeight()));
    vo.setProductGross(SheetUtils.tryToDecimal(row.getProductGross()));
    if (StringUtils.hasText(row.getSalesStatus())) {
      List<SysDictAllItem> salesStatusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "salesStatus",
          n -> sysDictService.getDictItems("SCM00006")
        );
      ProductVo finalVo = vo;
      salesStatusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getSalesStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setSalesStatus(i.getItemValue()),
          () ->
            ir.addError(
              "salesStatus",
              String.format(
                "必须为 %s 中之一",
                salesStatusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setIsMatchedAlibaba(SheetUtils.tryToBoolean(row.getIsMatchedAlibaba()));
    vo.setIsMatchedListing(SheetUtils.tryToBoolean(row.getIsMatchedListing()));
    if (StringUtils.hasText(row.getType())) {
      List<SysDictAllItem> typeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "type",
          n -> sysDictService.getDictItems("SCM00016")
        );
      ProductVo finalVo = vo;
      typeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setType(i.getItemValue()),
          () ->
            ir.addError(
              "type",
              String.format(
                "必须为 %s 中之一",
                typeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getLifeTag())) {
      List<SysDictAllItem> lifeTagItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "lifeTag",
          n -> sysDictService.getDictItems("SCM00208")
        );
      ProductVo finalVo = vo;
      lifeTagItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getLifeTag()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setLifeTag(i.getItemValue()),
          () ->
            ir.addError(
              "lifeTag",
              String.format(
                "必须为 %s 中之一",
                lifeTagItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getMetricOrBritish())) {
      List<SysDictAllItem> metricOrBritishItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "metricOrBritish",
          n -> sysDictService.getDictItems("SCM00007")
        );
      ProductVo finalVo = vo;
      metricOrBritishItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getMetricOrBritish()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setMetricOrBritish(i.getItemValue()),
          () ->
            ir.addError(
              "metricOrBritish",
              String.format(
                "必须为 %s 中之一",
                metricOrBritishItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setProductLength(SheetUtils.tryToDecimal(row.getProductLength()));
    vo.setProductWidth(SheetUtils.tryToDecimal(row.getProductWidth()));
    vo.setProductHeight(SheetUtils.tryToDecimal(row.getProductHeight()));
    vo.setProductNet(SheetUtils.tryToDecimal(row.getProductNet()));
    if (StringUtils.hasText(row.getLogisticsPriceType())) {
      List<SysDictAllItem> logisticsPriceTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "logisticsPriceType",
          n -> sysDictService.getDictItems("SCM00030")
        );
      ProductVo finalVo = vo;
      logisticsPriceTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getLogisticsPriceType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setLogisticsPriceType(i.getItemValue()),
          () ->
            ir.addError(
              "logisticsPriceType",
              String.format(
                "必须为 %s 中之一",
                logisticsPriceTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getPurchasePriceType())) {
      List<SysDictAllItem> purchasePriceTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "purchasePriceType",
          n -> sysDictService.getDictItems("SCM00031")
        );
      ProductVo finalVo = vo;
      purchasePriceTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPurchasePriceType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPurchasePriceType(i.getItemValue()),
          () ->
            ir.addError(
              "purchasePriceType",
              String.format(
                "必须为 %s 中之一",
                purchasePriceTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getPriceType())) {
      List<SysDictAllItem> priceTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "priceType",
          n -> sysDictService.getDictItems("SCM00032")
        );
      ProductVo finalVo = vo;
      priceTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPriceType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPriceType(i.getItemValue()),
          () ->
            ir.addError(
              "priceType",
              String.format(
                "必须为 %s 中之一",
                priceTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setCustomsCharges(SheetUtils.tryToDecimal(row.getCustomsCharges()));
    if (StringUtils.hasText(row.getCustomsCurrency())) {
      List<SysDictAllItem> customsCurrencyItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "customsCurrency",
          n -> sysDictService.getDictItems("SCM00015")
        );
      ProductVo finalVo = vo;
      customsCurrencyItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCustomsCurrency()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCustomsCurrency(i.getItemValue()),
          () ->
            ir.addError(
              "customsCurrency",
              String.format(
                "必须为 %s 中之一",
                customsCurrencyItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getSpecialProperties())) {
      List<SysDictAllItem> specialPropertiesItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "specialProperties",
          n -> sysDictService.getDictItems("SCM00009")
        );
      ProductVo finalVo = vo;
      List<String> specialPropertiesTexts = Arrays
        .stream(row.getSpecialProperties().split(","))
        .filter(StringUtils::hasText)
        .collect(Collectors.toList());
      finalVo.setSpecialProperties(
        specialPropertiesItems
          .stream()
          .filter(i -> specialPropertiesTexts.contains(i.getItemText()))
          .map(SysDictAllItem::getItemValue)
          .collect(Collectors.joining(","))
      );
    }
    if (StringUtils.hasText(row.getCustomsDiscounts())) {
      List<SysDictAllItem> customsDiscountsItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "customsDiscounts",
          n -> sysDictService.getDictItems("SCM00010")
        );
      ProductVo finalVo = vo;
      customsDiscountsItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCustomsDiscounts()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCustomsDiscounts(i.getItemValue()),
          () ->
            ir.addError(
              "customsDiscounts",
              String.format(
                "必须为 %s 中之一",
                customsDiscountsItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getCustomsBrand())) {
      List<SysDictAllItem> customsBrandItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "customsBrand",
          n -> sysDictService.getDictItems("SCM00011")
        );
      ProductVo finalVo = vo;
      customsBrandItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCustomsBrand()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCustomsBrand(i.getItemValue()),
          () ->
            ir.addError(
              "customsBrand",
              String.format(
                "必须为 %s 中之一",
                customsBrandItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getCustomsWeave())) {
      List<SysDictAllItem> customsWeaveItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "customsWeave",
          n -> sysDictService.getDictItems("SCM00012")
        );
      ProductVo finalVo = vo;
      customsWeaveItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCustomsWeave()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCustomsWeave(i.getItemValue()),
          () ->
            ir.addError(
              "customsWeave",
              String.format(
                "必须为 %s 中之一",
                customsWeaveItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getCheckType())) {
      List<SysDictAllItem> checkTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "checkType",
          n -> sysDictService.getDictItems("SCM00033")
        );
      ProductVo finalVo = vo;
      checkTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getCheckType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setCheckType(i.getItemValue()),
          () ->
            ir.addError(
              "checkType",
              String.format(
                "必须为 %s 中之一",
                checkTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setIsBatch(SheetUtils.tryToBoolean(row.getIsBatch()));
    if (StringUtils.hasText(row.getPutaway())) {
      List<SysDictAllItem> putawayItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "putaway",
          n -> sysDictService.getDictItems("SCM00034")
        );
      ProductVo finalVo = vo;
      putawayItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPutaway()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPutaway(i.getItemValue()),
          () ->
            ir.addError(
              "putaway",
              String.format(
                "必须为 %s 中之一",
                putawayItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setStocktaking(SheetUtils.tryToInteger(row.getStocktaking()));
    vo.setTransportCost(SheetUtils.tryToDecimal(row.getTransportCost()));
    vo.setIsCombo(SheetUtils.tryToBoolean(row.getIsCombo()));
    vo.setLxProductId(SheetUtils.tryToLong(row.getLxProductId()));
    // 处理关联字段“分类”
    if (
      !SheetUtils.isBlank(row.getClassifyName()) &&
      SheetUtils.isBlank(row.getClassify())
    ) {
      ClassifySearchParamPo classifySearchParam = new ClassifySearchParamPo();
      classifySearchParam.setLimit(2); // 最大只返回二行记录
      classifySearchParam.setNameEq(SheetUtils.trim(row.getClassifyName()));
      classifySearchParam.applySqlSegments();
      List<ClassifyItemVo> classifyMatches = classifyMapper.search(
        classifySearchParam
      );
      if (classifyMatches.size() == 0) {
        ir.addError("classifyName", "未能在分类管理中找到匹配的数据");
      } else if (classifyMatches.size() > 1) {
        ir.addError(
          "classifyName",
          "关联不唯一，在分类管理中找到多个匹配的数据"
        );
      } else {
        vo.setClassify(classifyMatches.get(0).getId());
      }
    }
    // 处理关联字段“品牌”
    if (
      !SheetUtils.isBlank(row.getBrandName()) &&
      SheetUtils.isBlank(row.getBrand())
    ) {
      BrandSearchParamPo brandSearchParam = new BrandSearchParamPo();
      brandSearchParam.setLimit(2); // 最大只返回二行记录
      brandSearchParam.setNameEq(SheetUtils.trim(row.getBrandName()));
      brandSearchParam.applySqlSegments();
      List<BrandItemVo> brandMatches = brandMapper.search(brandSearchParam);
      if (brandMatches.size() == 0) {
        ir.addError("brandName", "未能在品牌管理中找到匹配的数据");
      } else if (brandMatches.size() > 1) {
        ir.addError("brandName", "关联不唯一，在品牌管理中找到多个匹配的数据");
      } else {
        vo.setBrand(brandMatches.get(0).getId());
      }
    }
    // 处理关联字段“开发人”
    if (
      !SheetUtils.isBlank(row.getDeveloperName()) &&
      SheetUtils.isBlank(row.getDeveloper())
    ) {
      SysUserSearch developerSearchParam = new SysUserSearch();
      developerSearchParam.setLimit(2); // 最大只返回二行记录
      developerSearchParam.setNameEq(SheetUtils.trim(row.getDeveloperName()));
      developerSearchParam.applySqlSegments();
      List<SysUserItemVo> developerMatches = sysUserMapper.search(
        developerSearchParam
      );
      if (developerMatches.size() == 0) {
        ir.addError("developerName", "未能在用户中找到匹配的数据");
      } else if (developerMatches.size() > 1) {
        ir.addError("developerName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setDeveloper(developerMatches.get(0).getId());
      }
    }
    // 处理关联字段“产品负责人”
    if (
      !SheetUtils.isBlank(row.getPrincipalName()) &&
      SheetUtils.isBlank(row.getPrincipal())
    ) {
      SysUserSearch principalSearchParam = new SysUserSearch();
      principalSearchParam.setLimit(2); // 最大只返回二行记录
      principalSearchParam.setNameEq(SheetUtils.trim(row.getPrincipalName()));
      principalSearchParam.applySqlSegments();
      List<SysUserItemVo> principalMatches = sysUserMapper.search(
        principalSearchParam
      );
      if (principalMatches.size() == 0) {
        ir.addError("principalName", "未能在用户中找到匹配的数据");
      } else if (principalMatches.size() > 1) {
        ir.addError("principalName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setPrincipal(
          principalMatches
            .stream()
            .map(SysUserItemVo::getId)
            .collect(Collectors.toList())
        );
      }
    }
    // 处理关联字段“采购员”
    if (
      !SheetUtils.isBlank(row.getBuyerName()) &&
      SheetUtils.isBlank(row.getBuyer())
    ) {
      SysUserSearch buyerSearchParam = new SysUserSearch();
      buyerSearchParam.setLimit(2); // 最大只返回二行记录
      buyerSearchParam.setNameEq(SheetUtils.trim(row.getBuyerName()));
      buyerSearchParam.applySqlSegments();
      List<SysUserItemVo> buyerMatches = sysUserMapper.search(buyerSearchParam);
      if (buyerMatches.size() == 0) {
        ir.addError("buyerName", "未能在用户中找到匹配的数据");
      } else if (buyerMatches.size() > 1) {
        ir.addError("buyerName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setBuyer(buyerMatches.get(0).getId());
      }
    }
    // 处理关联字段“分组”
    if (
      !SheetUtils.isBlank(row.getGroupName()) &&
      SheetUtils.isBlank(row.getGroup())
    ) {
      ProductGroupSearchParamPo groupSearchParam =
        new ProductGroupSearchParamPo();
      groupSearchParam.setLimit(2); // 最大只返回二行记录
      groupSearchParam.setNameEq(SheetUtils.trim(row.getGroupName()));
      groupSearchParam.applySqlSegments();
      List<ProductGroupItemVo> groupMatches = productGroupMapper.search(
        groupSearchParam
      );
      if (groupMatches.size() == 0) {
        ir.addError("groupName", "未能在分组管理中找到匹配的数据");
      } else if (groupMatches.size() > 1) {
        ir.addError("groupName", "关联不唯一，在分组管理中找到多个匹配的数据");
      } else {
        vo.setGroup(groupMatches.get(0).getId());
      }
    }
    // 处理关联字段“默认仓库”
    if (
      !SheetUtils.isBlank(row.getDefaultWarehouseName()) &&
      SheetUtils.isBlank(row.getDefaultWarehouse())
    ) {
      WarehouseSearchParamPo defaultWarehouseSearchParam =
        new WarehouseSearchParamPo();
      defaultWarehouseSearchParam.setLimit(2); // 最大只返回二行记录
      defaultWarehouseSearchParam.setNameEq(
        SheetUtils.trim(row.getDefaultWarehouseName())
      );
      defaultWarehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> defaultWarehouseMatches = warehouseMapper.search(
        defaultWarehouseSearchParam
      );
      if (defaultWarehouseMatches.size() == 0) {
        ir.addError(
          "defaultWarehouseName",
          "未能在仓库即时库存中找到匹配的数据"
        );
      } else if (defaultWarehouseMatches.size() > 1) {
        ir.addError(
          "defaultWarehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setDefaultWarehouse(defaultWarehouseMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<ProductImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<ProductImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            ProductImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(ProductImportPo row, AnalysisContext cxt) {
              ProductVo vo = new ProductVo();
              ImportRow<ProductImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<ProductImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<ProductImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      ProductVo vo = new ProductVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    ProductSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "classify",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ProductItemVo) r).getClassifyName())
          )
      );
      exportOptions.addFieldMappingOption(
        "brand",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ProductItemVo) r).getBrandName())
          )
      );
      exportOptions.addFieldMappingOption(
        "developer",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ProductItemVo) r).getDeveloperName())
          )
      );
      exportOptions.addFieldMappingOption(
        "principal",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ProductItemVo) r).getPrincipalName())
          )
      );
      exportOptions.addFieldMappingOption(
        "buyer",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ProductItemVo) r).getBuyerName())
          )
      );
      exportOptions.addFieldMappingOption(
        "salesStatus",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00006")
      );
      exportOptions.addFieldMappingOption(
        "type",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00016")
      );
      exportOptions.addFieldMappingOption(
        "group",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ProductItemVo) r).getGroupName())
          )
      );
      exportOptions.addFieldMappingOption(
        "lifeTag",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00208")
      );
      exportOptions.addStringFields(
        "spuName",
        "spu",
        "name",
        "sku",
        "isOpen",
        "model",
        "unit",
        "classifyName",
        "brandName",
        "developerName",
        "principalName",
        "buyerName",
        "accessoriesNum",
        "salesStatus",
        "isMatchedAlibaba",
        "isMatchedListing",
        "type",
        "productType",
        "groupName",
        "lifeTag",
        "info1",
        "info2",
        "epColor",
        "material",
        "tradeName"
      );

      String fileName = String.format(
        "产品(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> salesStatusItems = sysDictService.getDictItems(
      "SCM00006"
    );
    List<SysDictAllItem> typeItems = sysDictService.getDictItems("SCM00016");
    List<SysDictAllItem> lifeTagItems = sysDictService.getDictItems("SCM00208");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<ProductExcelPo> items = new ArrayList<ProductExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<ProductItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<ProductItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (ProductItemVo item : list) {
        ProductExcelPo excel = new ProductExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getIsOpen() != null) {
          excel.setIsOpen(item.getIsOpen() ? "是" : "否");
        }
        if (item.getSalesStatus() != null) {
          salesStatusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getSalesStatus()))
            .findFirst()
            .ifPresent(i -> excel.setSalesStatus(i.getItemText()));
        }
        if (item.getIsMatchedAlibaba() != null) {
          excel.setIsMatchedAlibaba(item.getIsMatchedAlibaba() ? "是" : "否");
        }
        if (item.getIsMatchedListing() != null) {
          excel.setIsMatchedListing(item.getIsMatchedListing() ? "是" : "否");
        }
        if (item.getType() != null) {
          typeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getType()))
            .findFirst()
            .ifPresent(i -> excel.setType(i.getItemText()));
        }
        if (item.getLifeTag() != null) {
          lifeTagItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getLifeTag()))
            .findFirst()
            .ifPresent(i -> excel.setLifeTag(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "产品(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(ProductExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过品名查询产品主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByName(String name) {
    return this.baseMapper.getIdByName(name);
  }

  /**
   * 通过品名查询产品多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByName(List<String> list) {
    return this.baseMapper.getIdsByName(list);
  }

  /**
   * 通过产品主键查询品名
   */
  @Override
  public String getNameById(Long id) {
    return this.baseMapper.getNameById(id);
  }

  /**
   * 通过产品主键查询品名列表
   */
  @Override
  public List<String> getNameByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getNameByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("name"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 产品的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public ProductVo getVoById(Long id) throws Exception {
    ProductVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    ProductSupplierQuoteSearchParamPo productSupplierQuoteSearchParamPo =
      new ProductSupplierQuoteSearchParamPo();
    productSupplierQuoteSearchParamPo.setParentProduct(id);
    productSupplierQuoteSearchParamPo.getExtendData().put("queryMode", "sub");
    productSupplierQuoteSearchParamPo
      .getExtendData()
      .put("queryParent", "Product");
    productSupplierQuoteSearchParamPo.applySqlSegments();
    vo.setProductSupplierQuote(
      productSupplierQuoteService.search(productSupplierQuoteSearchParamPo)
    );

    ProductIngredientsSearchParamPo ingredientsSearchParamPo =
      new ProductIngredientsSearchParamPo();
    ingredientsSearchParamPo.setProductId(id);
    ingredientsSearchParamPo.getExtendData().put("queryMode", "sub");
    ingredientsSearchParamPo.getExtendData().put("queryParent", "Product");
    ingredientsSearchParamPo.applySqlSegments();
    vo.setIngredients(
      productIngredientsService.search(ingredientsSearchParamPo)
    );

    ProductPackSearchParamPo packsSearchParamPo =
      new ProductPackSearchParamPo();
    packsSearchParamPo.setProductId(id);
    packsSearchParamPo.getExtendData().put("queryMode", "sub");
    packsSearchParamPo.getExtendData().put("queryParent", "Product");
    packsSearchParamPo.applySqlSegments();
    vo.setPacks(productPackService.search(packsSearchParamPo));

    ProductCustomsPriceSearchParamPo customsSearchParamPo =
      new ProductCustomsPriceSearchParamPo();
    customsSearchParamPo.setProductId(id);
    customsSearchParamPo.getExtendData().put("queryMode", "sub");
    customsSearchParamPo.getExtendData().put("queryParent", "Product");
    customsSearchParamPo.applySqlSegments();
    vo.setCustoms(productCustomsPriceService.search(customsSearchParamPo));

    ProductQualityCheckSearchParamPo checksSearchParamPo =
      new ProductQualityCheckSearchParamPo();
    checksSearchParamPo.setProductId(id);
    checksSearchParamPo.getExtendData().put("queryMode", "sub");
    checksSearchParamPo.getExtendData().put("queryParent", "Product");
    checksSearchParamPo.applySqlSegments();
    vo.setChecks(productQualityCheckService.search(checksSearchParamPo));

    ProductInventorySearchParamPo inventorysSearchParamPo =
      new ProductInventorySearchParamPo();
    inventorysSearchParamPo.setItemId(id);
    inventorysSearchParamPo.getExtendData().put("queryMode", "sub");
    inventorysSearchParamPo.getExtendData().put("queryParent", "Product");
    inventorysSearchParamPo.applySqlSegments();
    vo.setInventorys(productInventoryService.search(inventorysSearchParamPo));

    ProductSubSearchParamPo subProductsSearchParamPo =
      new ProductSubSearchParamPo();
    subProductsSearchParamPo.setProductId(id);
    subProductsSearchParamPo.getExtendData().put("queryMode", "sub");
    subProductsSearchParamPo.getExtendData().put("queryParent", "Product");
    subProductsSearchParamPo.applySqlSegments();
    vo.setSubProducts(productSubService.search(subProductsSearchParamPo));

    ProductSpuSubSearchParamPo subProductsSpuSearchParamPo =
      new ProductSpuSubSearchParamPo();
    subProductsSpuSearchParamPo.setProductId(id);
    subProductsSpuSearchParamPo.getExtendData().put("queryMode", "sub");
    subProductsSpuSearchParamPo.getExtendData().put("queryParent", "Product");
    subProductsSpuSearchParamPo.applySqlSegments();
    vo.setSubProductsSpu(
      productSpuSubService.search(subProductsSpuSearchParamPo)
    );

    return vo;
  }

  /**
   * 分页查询产品
   * @param search 查询条件
   * @return 产品分页查询结果
   */
  @Override
  public Page<ProductItemVo> pageSearch(ProductSearchParamPo search) {
    Page<ProductItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(ProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 产品快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'ProductOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<ProductItemVo>> searchOptions(
    ProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询产品
   * @param search 查询条件
   * @return 产品列表查询结果
   */
  @Override
  public List<ProductItemVo> search(ProductSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询产品最后更新时间
   * @param search 查询条件
   * @return 产品最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(ProductSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 根据时间获取
   */
  /**
   * 根据时间获取表单确定操作
   */
  @Override
  public void syncByTimeConfirm(JSONObject data) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/Product_syncByTime_confirm.js",
      data,
      this
    );
  }

  /**
   * 根据sku获取产品
   */
  /**
   * 根据sku获取产品表单确认操作
   */
  @Override
  public void getProductBySkuConfirm(JSONObject data) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/Product_getProductBySku_confirm.js",
      data,
      this
    );
  }

  /**
   * 同步领星产品数据
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了同步领星产品数据操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void syncPro() throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/Product_syncPro.js",
      null,
      null,
      this
    );
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    ProductSearchParamPo search = new ProductSearchParamPo();
    return MapUtil
      .builder()
      .put("Product", this.baseMapper.productCount(search))
      .put("GeneralProduct", this.baseMapper.generalProductCount(search))
      .put(
        "CombinationProduct",
        this.baseMapper.combinationProductCount(search)
      )
      .put("RawMaterials", this.baseMapper.rawMaterialsCount(search))
      .put("Spu", this.baseMapper.spuCount(search))
      .build();
  }

  /**
   * 按SKU//全部
   */
  @Override
  public List<ProductItemVo> product(ProductSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.product(search);
  }

  /**
   * 按SKU//全部分页
   */
  @Override
  public Page<ProductItemVo> productPage(ProductSearchParamPo search) {
    Page<ProductItemVo> productPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return productPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return productPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    productPage =
      this.baseMapper.productPage(
          search.toPage(this.baseMapper.productCount(search)),
          search
        );
    List<Long> recordIds = productPage
      .getRecords()
      .stream()
      .map(ProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return productPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return productPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    productPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return productPage;
  }

  /**
   * 查询按SKU//全部最后更新时间
   * @param search 查询条件
   * @return 按SKU//全部最后更新时间
   */
  @Override
  public Date productLastUpdateTime(ProductSearchParamPo search) {
    return this.baseMapper.productLastUpdateTime(search);
  }

  /**
   * 按SKU//普通商品
   */
  @Override
  public List<ProductItemVo> generalProduct(ProductSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.generalProduct(search);
  }

  /**
   * 按SKU//普通商品分页
   */
  @Override
  public Page<ProductItemVo> generalProductPage(ProductSearchParamPo search) {
    Page<ProductItemVo> generalProductPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return generalProductPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return generalProductPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    generalProductPage =
      this.baseMapper.generalProductPage(
          search.toPage(this.baseMapper.generalProductCount(search)),
          search
        );
    List<Long> recordIds = generalProductPage
      .getRecords()
      .stream()
      .map(ProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return generalProductPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return generalProductPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    generalProductPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return generalProductPage;
  }

  /**
   * 查询按SKU//普通商品最后更新时间
   * @param search 查询条件
   * @return 按SKU//普通商品最后更新时间
   */
  @Override
  public Date generalProductLastUpdateTime(ProductSearchParamPo search) {
    return this.baseMapper.generalProductLastUpdateTime(search);
  }

  /**
   * 按SKU//组合产品
   */
  @Override
  public List<ProductItemVo> combinationProduct(ProductSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.combinationProduct(search);
  }

  /**
   * 按SKU//组合产品分页
   */
  @Override
  public Page<ProductItemVo> combinationProductPage(
    ProductSearchParamPo search
  ) {
    Page<ProductItemVo> combinationProductPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return combinationProductPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return combinationProductPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    combinationProductPage =
      this.baseMapper.combinationProductPage(
          search.toPage(this.baseMapper.combinationProductCount(search)),
          search
        );
    List<Long> recordIds = combinationProductPage
      .getRecords()
      .stream()
      .map(ProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return combinationProductPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return combinationProductPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    combinationProductPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return combinationProductPage;
  }

  /**
   * 查询按SKU//组合产品最后更新时间
   * @param search 查询条件
   * @return 按SKU//组合产品最后更新时间
   */
  @Override
  public Date combinationProductLastUpdateTime(ProductSearchParamPo search) {
    return this.baseMapper.combinationProductLastUpdateTime(search);
  }

  /**
   * 按SKU//原材料
   */
  @Override
  public List<ProductItemVo> rawMaterials(ProductSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.rawMaterials(search);
  }

  /**
   * 按SKU//原材料分页
   */
  @Override
  public Page<ProductItemVo> rawMaterialsPage(ProductSearchParamPo search) {
    Page<ProductItemVo> rawMaterialsPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return rawMaterialsPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return rawMaterialsPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    rawMaterialsPage =
      this.baseMapper.rawMaterialsPage(
          search.toPage(this.baseMapper.rawMaterialsCount(search)),
          search
        );
    List<Long> recordIds = rawMaterialsPage
      .getRecords()
      .stream()
      .map(ProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return rawMaterialsPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return rawMaterialsPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    rawMaterialsPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return rawMaterialsPage;
  }

  /**
   * 查询按SKU//原材料最后更新时间
   * @param search 查询条件
   * @return 按SKU//原材料最后更新时间
   */
  @Override
  public Date rawMaterialsLastUpdateTime(ProductSearchParamPo search) {
    return this.baseMapper.rawMaterialsLastUpdateTime(search);
  }

  /**
   * 按SPU
   */
  @Override
  public List<ProductItemVo> spu(ProductSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.spu(search);
  }

  /**
   * 按SPU分页
   */
  @Override
  public Page<ProductItemVo> spuPage(ProductSearchParamPo search) {
    Page<ProductItemVo> spuPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return spuPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return spuPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    spuPage =
      this.baseMapper.spuPage(
          search.toPage(this.baseMapper.spuCount(search)),
          search
        );
    List<Long> recordIds = spuPage
      .getRecords()
      .stream()
      .map(ProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return spuPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return spuPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    spuPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return spuPage;
  }

  /**
   * 查询按SPU最后更新时间
   * @param search 查询条件
   * @return 按SPU最后更新时间
   */
  @Override
  public Date spuLastUpdateTime(ProductSearchParamPo search) {
    return this.baseMapper.spuLastUpdateTime(search);
  }

  /**
   * 查询库存
   */
  @Override
  public List<ProductGetStorageBinResult> getStorageBin(
    ProductGetStorageBinParam param
  ) {
    return this.baseMapper.getStorageBin(param);
  }

  /**
   * 查询历史采购订单
   */
  @Override
  public Page<ProductGetPurchaseOrderResult> getPurchaseOrder(
    ProductGetPurchaseOrderParam param
  ) {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    if (currentUser != null) {
      param.setCurrentUserId(currentUser.getUserId());
    }
    param.setDisableDataPremissions(true);
    return this.baseMapper.getPurchaseOrder(param.toPage(), param);
  }
}
